package com.yicong.ants.ui.me;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;

import com.alibaba.security.common.view.GifImageView;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cchao.simplelib.core.AndroidHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.PrefHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.UrlUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.account.NewYearGoodsActivity;
import com.yicong.ants.bean.account.UserBean;
import com.yicong.ants.bean.global.ClientConfig;
import com.yicong.ants.databinding.MeAntFragmentBinding;
import com.yicong.ants.databinding.UserLevelUpdateDialogBinding;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.OkHttpManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.circle.ad.AdPublishActivity2;
import com.yicong.ants.ui.coin.TransActivity;
import com.yicong.ants.ui.coin.UserCoinActivity;
import com.yicong.ants.ui.me.recommend.MyTeamActivity;
import com.yicong.ants.ui.me.recommend.ShareActivity;
import com.yicong.ants.ui.present.ExchangeYcActivity;
import com.yicong.ants.ui.present.TaskCenterActivity;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.GuideHelper;
import com.yicong.ants.utils.NoviceGuidance.GuidancePopup;
import com.yicong.ants.utils.PermissionsChecker;
import com.yicong.ants.utils.SPUtils;
import com.yicong.ants.view.component.SimpleComponent;
import com.yicong.ants.view.component.TaskCenterGuideComponent;
import com.zx.sdk.util.ConfigHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * 我的页面 可配置
 *
 * @author cchao
 * @version 2019-05-21.
 */
public class MeAntFragment extends BaseStatefulFragment<MeAntFragmentBinding> implements View.OnClickListener {
    boolean isResumed;
    boolean mIsHidden;

    @Override
    protected int getLayoutId() {
        return R.layout.me_ant_fragment;
    }

    @Override
    protected void initEventAndData() {
        levelIv = getView().findViewById(R.id.level_iv);
        mDataBind.mScrollView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                v.removeOnLayoutChangeListener(this);
                mDataBind.layoutGroup.setMinimumHeight(v.getHeight());
            }
        });

        mDataBind.setClick(this);
        // 下拉刷新
        mDataBind.swipeRefresh.setOnRefreshListener(this::onLoadDashBoard);
        updateInfo();
        onLoadDashBoard();

        if ((boolean) SPUtils.get(getContext(), "isFirstMe", true)) {
            mDataBind.ivUserPlace.post(() -> {
                showGuidance1();
            });
        }
        mDataBind.actionBar.getBackground().setAlpha(0);
        mDataBind.mScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            float alp = scrollY * 0.02f;
            if (alp < 0) {
                alp = 0;
            } else if (alp > 1) {
                alp = 1;
            }
            mDataBind.actionBar.getBackground().setAlpha((int) (255F * alp));
        });
        String newListKey = "new_list";
        if (ZzConfigs.getClientConf().getWeb_url().containsKey(newListKey) && !BuildConfig.STORE) {
            mDataBind.newsll.setVisibility(View.VISIBLE);
            mDataBind.newsll.setOnClickListener(view -> ZzConfigs.toWebActivityByUrl(getContext(), newListKey));
        }
        mDataBind.setIsNewYear(ZzConfigs.getClientConf().isNewYear());
        mDataBind.ycDh.setVisibility(ZzConfigs.getClientConf().yc_task_coin_exchange_switch ? View.VISIBLE : View.GONE);
        ImageView advIv = getView().findViewById(R.id.advIv);
        ClientConfig.WebUrl advWebUrl = ZzConfigs.getWebUrl("ad_uCenter");
        if (advWebUrl.img_url != null && !advWebUrl.img_url.isEmpty()) {
            Glide.with(requireActivity()).asBitmap()
                    .load(advWebUrl.img_url)
                    .into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            advIv.setImageBitmap(resource);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
            advIv.setOnClickListener(v -> {
                ZzConfigs.toWebActivity(getContext(), null, advWebUrl.url);
                HashMap<String, Object> map = new HashMap<>();
                map.put(advWebUrl.url, "click");
                MobclickAgent.onEventObject(getContext(), "KEY_USER_INFO_ADV_1", map);
            });
        }
    }

    private void showGuidance1() {
        if (UserManager.notLogin()) {
            return;
        }
        if (!UserManager.getUserBean().getIsAuth() && UserManager.getUserBean().getCoin_float() == 10) {
            if (!PrefHelper.isFirstTimes(Constants.Prefs.task_step)) {
                return;
            }
            GuidancePopup popup = new GuidancePopup(getContext());
            popup.setOnClickListener(view -> {
                showGuidance2();
            });
            GuidancePopup.StepBean stepBean = new GuidancePopup.StepBean();
            stepBean.view = mDataBind.ivUserPlace;
            stepBean.status = 0;
            popup.setStep(stepBean);
            popup.showDialog(mDataBind.swipeRefresh);
        }
    }

    private void showGuidance2() {
        GuidancePopup popup = new GuidancePopup(getContext());
        popup.setOnClickListener(view -> {
            SPUtils.put(getContext(), "isFirstMe", false);
        });
        GuidancePopup.StepBean stepBean = new GuidancePopup.StepBean();
        stepBean.view = mDataBind.jiangLi;
        stepBean.status = 1;
        popup.setStep(stepBean);
        popup.showDialog(mDataBind.swipeRefresh);
    }

    private void checkGuide1() {
        if (UserManager.notLogin()) {
            return;
        }

        if (!UserManager.getUserBean().getIsAuth() && UserManager.getUserBean().getCoin_float() == 10) {
            if (!PrefHelper.isFirstTimes(Constants.Prefs.task_step)) {
                return;
            }

            RxHelper.timerConsumer(200, aLong -> {
                mDataBind.starTextField.post(() -> {
                    SimpleComponent component = new SimpleComponent();
                    component.setContent("请先完成实名认证");
                    GuideHelper.showGuideView(this.getActivity(), mDataBind.starTextField, component);
                });
            });
        }
    }

    private void checkGuide2() {
        if (UserManager.notLogin()) {
            return;
        }

        if (UserManager.getUserBean().getIsAuth() && UserManager.getUserBean().getCoin_float() == 10) {
            if (!PrefHelper.isFirstTimes(Constants.Prefs.task_step1)) {
                return;
            }

            mDataBind.taskField.post(() ->
                    GuideHelper.showCircleGuideView(this.getActivity(), 20
                            , mDataBind.taskField, new TaskCenterGuideComponent()));
        }
    }

    void onLoadDashBoard() {
        if (!UserManager.isLogin()) {
            mDataBind.swipeRefresh.setRefreshing(false);
            return;
        }
        RxHelper.timerConsumer(500, aLong -> {
            //
            addSubscribe(UserManager.refreshDashboard(str -> {
                mDataBind.totalCoin.setText(str);
                mDataBind.swipeRefresh.setRefreshing(false);
            }));
        });
    }

    @Override
    protected void onLoadData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1315:
                trySynAdCode();
                break;
            default:
                break;
        }
    }

    private void trySynAdCode() {
        // 重新加载 config
        AmapHelper.startLocation(mContext, aMapLocation -> {
            // 更新配置项
            BusinessHelper.loadIndexConfig(bool -> {
                // nothing
            });
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        isResumed = true;
        levelIv.play(1);
        ThreadUtils.runOnUiThreadDelayed(() -> {
            if (mDataBind.suspensionAdContainer.getChildCount() == 0 && ConfigHelper.canShowSuspension()) {
                AdManager.showSuspension(requireActivity(), mDataBind.suspensionAdContainer);
            }
        }, 1);
    }

    @Override
    public void onPause() {
        super.onPause();
        isResumed = false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) levelIv.play(1);
        mIsHidden = hidden;
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Update_Me_Info:
            case Constants.Event.Login_Suc:
            case Constants.Event.Login_Out:
                updateInfo();
                break;
            case Constants.Event.Refresh_Dashboard_Fail:
                mDataBind.swipeRefresh.setRefreshing(false);
                break;
            case Constants.Event.Expect_Refresh_Dashboard:
                onLoadDashBoard();
                break;
        }
    }

    private GifImageView levelIv;

    private void updateInfo() {
        UserBean userBean = UserManager.getUserBean();
        mDataBind.setUser(userBean);
        if (UserManager.notLogin()) {
            mDataBind.avatar.setImageResource(R.mipmap.my_avatar_default);
        }
        if (userBean != null) {
            switch (userBean.getLevel()) {
                case "0":
                    levelIv.setGifResource(R.drawable.level_0_gif);
                    break;
                case "1":
                    levelIv.setGifResource(R.drawable.level_1_gif);
                    break;
                case "2":
                    levelIv.setGifResource(R.drawable.level_2_gif);
                    break;
                case "3":
                    levelIv.setGifResource(R.drawable.level_3_gif);
                    break;
                case "4":
                    levelIv.setGifResource(R.drawable.level_4_gif);
                    break;
                case "5":
                    levelIv.setGifResource(R.drawable.level_5_gif);
                    break;
            }
        }
        boolean isAuth = false;
        if (UserManager.isLogin() && userBean.getIsAuth()) {
            isAuth = true;
        }
//        mDataBind.authText.setNormalBackgroundColor(UiHelper.getColor(isAuth ? R.color.bg_me_auth : R.color.red_color));
//        mDataBind.authText.setTextColor(UiHelper.getColor(isAuth ? R.color.text_333 : R.color.white));

        mDataBind.authLabel.setImageResource(isAuth ? R.drawable.mine_have_auth : R.drawable.mine_no_auth);
        UiHelper.setVisibleElseGone(mDataBind.traderField, false);
        UiHelper.setVisibleElseGone(mDataBind.mchField, false);
        mDataBind.uid.getPaint().setFakeBoldText(UserManager.haveNiceNumber());
        if (UserManager.isLogin()) {
//            UiHelper.setVisibleElseGone(mDataBind.starTextField, userBean.getRole() == 0);
            UiHelper.setVisibleElseGone(mDataBind.traderField, userBean.getRole() == 1);
            UiHelper.setVisibleElseGone(mDataBind.mchField, userBean.getRole() == 2);
        }
        //年货节的活动信息 未登录则清除，登陆则根据内容展示
        NewYearGoodsActivity newYearGoodsActivity = null;
        if (UserManager.isLogin()) {
            newYearGoodsActivity = userBean.getActivity();
        }
        mDataBind.setActivity(newYearGoodsActivity);
        showRewardDialog();
//        checkGuide1();
//        checkGuide2();
    }

    boolean dialogShowed = false;

    void showRewardDialog() {
        if (UserManager.notLogin() || StringHelper.isEmpty(UserManager.getUserBean().getLevel_rewards())) {
            return;
        }

        if (dialogShowed) {
            return;
        }
        String rewardAmount = UserManager.getUserBean().getLevel_rewards().split("_")[1];

        Dialog dialog = new Dialog(mContext);
        UserLevelUpdateDialogBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.user_level_update_dialog, null, false);
        binding.field.setOnClickListener(v -> {
            dialog.dismiss();
        });
        binding.amountText.setText(rewardAmount);
        dialog.setContentView(binding.getRoot());
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setOnDismissListener(dialog1 -> {
            dialogShowed = false;
            //
            addSubscribe(RetrofitHelper.getApis().receiveLevelRewards()
                    .compose(RxHelper.toMain())
                    .subscribe(respBean -> {
                        if (respBean.isCodeFail()) {
                            showToast(respBean.getMsg());
                        }
                    }, RxHelper.getErrorTextConsumer(MeAntFragment.this)));
        });

        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0; // 新位置Y坐标
        lp.width = UiHelper.getScreenWidth(); // 宽度
        dialogWindow.setAttributes(lp);
        dialog.show();
        dialogShowed = true;
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.user_field:
                if (UserManager.isLogin()) {
                    Router.turnTo(mContext, UserInfoActivity.class).start();
                } else {
                    UserManager.routeLogin(mContext);
                }
                break;
            case R.id.user_id_field:
                if (UserManager.isLogin()) {
                    UserBean user = UserManager.getUserBean();
                    String copyContent = user.isHave_nice_number() ? user.getNice_number() : user.getId();
                    AndroidHelper.setClipboardData(copyContent, () -> {
                        //
                        showToast("蚁丛号：" + copyContent + " 已复制");
                    });
                }
                break;
            case R.id.trans_field:
                Router.turnTo(mContext, TransActivity.class).checkLogin(true).start();
                break;
            case R.id.lottery:
                ZzConfigs.toWebActivityByUrl(mContext, "lottery");
                break;
            case R.id.child_field:
            case R.id.contribution_field:
                Router.turnTo(mContext, MyTeamActivity.class)
                        .checkLogin(true)
                        .start();
                break;
            case R.id.settings:
                Router.turnTo(mContext, SettingsActivity.class).start();
                break;
            case R.id.profit_field:
                BusinessHelper.showDev();
                break;
            case R.id.recommend_field:
                if (UserManager.isNotLoginElseTurn(mContext)) {
                    return;
                }
                Router.turnTo(mContext, ShareActivity.class).start();
                break;
            case R.id.coin_field:
                Router.turnTo(mContext, UserCoinActivity.class).checkLogin(true).start();
                break;
            case R.id.energy_field:
//                if (UserManager.notLogin()) {
//                    return;
//                }
//
//                EventHelper.reportEvent("energy_center");
//                ZzConfigs.toWebActivityByUrl(mContext, "energy");
////                EnergyHelper.clickEnergyTask((BaseActivity) getActivity(), AntsAdHelper.Position.energy_task_mine);
                break;
            case R.id.star_text_field:
                UiHelper.showConfirmActionDialog(mContext, "是否刷新星级", (dialog, which) -> {
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().refreshStar()
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                hideProgress();
                                if (respBean.isCodeFail()) {
                                    showToast(respBean.getMsg());
                                    return;
                                }
                                // 星级变化
                                if (!UserManager.getUserBean().getLevel().equalsIgnoreCase(respBean.getData())) {
                                    onLoadDashBoard();
                                }
                            }, RxHelper.getHideProgressConsumer(MeAntFragment.this)));
                });
                break;
            case R.id.task_field:
                if (UserManager.notLogin()) {
                    Router.turnTo(mContext, TaskCenterActivity.class)
                            .checkLogin(true)
                            .start();
                    return;
                }
                if (!PermissionsChecker.checkPermissions(getContext(), Constants.LOCATION)) {
                    UiHelper.showConfirmDialog(requireActivity(), "权限申请", "需要获取“手机定位”、“访问本地存储”、”手机“权限，开启后将用于加密数据，保障您的数据使用安全",
                            (dialog, which) -> {
                                switch (which) {
                                    case DialogInterface.BUTTON_POSITIVE:
                                        new RxPermissions(this)
                                                .request(Constants.LOCATION)
                                                .subscribe(aBoolean -> {
                                                    if (aBoolean) {
                                                        goTaskCenter();
                                                    } else {
                                                        ToastUtils.showLong("没有权限，无法进入任务中心");
                                                    }
                                                });
                                        break;
                                    case DialogInterface.BUTTON_NEGATIVE:
                                        ToastUtils.showLong("没有权限，无法进入任务中心");
                                        break;
                                }
                            });
                    return;
                } else {
                    goTaskCenter();
                }
                break;
            case R.id.nice_number_filed:
                ZzConfigs.toWebActivityByUrl(mContext, "project_nice_number");
                break;
            case R.id.ad:
                Router.turnTo(mContext, AdPublishActivity2.class).start();
                break;
            case R.id.v_code:
                if (UserManager.isNotAuthElseTurn(mContext)) {
                    return;
                }
                BusinessHelper.showVourchCode(mDisposable, getActivity());
                break;
            case R.id.ychat:
                if (UserManager.isNotAuthElseTurn(mContext)) {
                    return;
                }

                Uri uri = Uri.parse(Constants.getWebUrl("ychat"));
                intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                break;
            case R.id.my_trans_qr:
                if (UserManager.isNotAuthElseTurn(mContext)) {
                    return;
                }

                // 显示转赠码
                Map<String, String> map2 = new HashMap<>();
                map2.put("id", "11040");
                map2.put("uid", UserManager.getUserId());
                String content = UrlUtil.buildUrl(Constants.Url.Route_App_Url, map2);
                Dialogs.showTransQr(getActivity(), content);
                break;
            case R.id.chat_business:
                if (UserManager.notLogin()) {
                    UiHelper.showToast("请先登录账号");
                    return;
                }
                Map<String, String> map = new HashMap<>();
                map.put("c1", UserManager.getMobile());
                map.put("c2", UserManager.getUserId());
                map.put("c3", "android");
                UserBean userBean = UserManager.getUserBean();
                if (StringHelper.isNotEmpty(userBean.getId_card_name())) {
                    map.put("c4", userBean.getId_card_name());
                    map.put("c5", "星级：" + userBean.getLevel() + " 活跃度：" + userBean.getEnergy());
                }
                String endUrl = UrlUtil.buildUrl(Constants.Customer_Chat, map);

                ZzConfigs.toWebActivityCheckLogin(mContext, "客服中心", endUrl);
                break;
            case R.id.total_coin:
                if (!mDataBind.swipeRefresh.isRefreshing()) {
                    mDataBind.swipeRefresh.setRefreshing(true);
                    onLoadDashBoard();
                }
                break;
//            case R.id.to_auth_field:
//                Router.turnTo(mContext, UserInfoActivity.class)
//                    .start();
//                break;
//            case R.id.tel:
//                IntentHelper.tel(getString(R.string.app_tel_num), mContext);
//                break;
            case R.id.new_year_goods_activity_go_web:
                RouterHelper.router(getActivity(), UserManager.getUserBean().getActivity().getUrl());
                break;
            case R.id.chain_app:
                String url = ZzConfigs.getWebUrl("chain_app").getUrl();
                Map<String, String> params = OkHttpManager.getCommonParams();
                for (String key : params.keySet()) {
                    url = UrlUtil.appendParameterCompat(url, key, params.get(key));
                }
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                break;
            case R.id.yc_dh:
                if (UserManager.isLogin()) {
                    Router.turnTo(mContext, ExchangeYcActivity.class).start();
                } else {
                    UserManager.routeLogin(mContext);
                }
                break;
            case R.id.yc_zh:
                ZzConfigs.toWebActivityByUrlNoTitle(mContext, "yc_transfer_center");
                break;
            case R.id.yc_qd:
                ZzConfigs.toWebActivityByUrlNoTitle(mContext, "yc_qdwc_download");
                break;
            case R.id.my_fans:
                Router.turnTo(mContext, FansListActivity.class).start();
                break;
        }
    }

    private void goTaskCenter() {
        Logs.d("UserManager.getUserBean().getLocation_code() " + UserManager.getUserBean().getLocation_code());
        // 未获取到归属城市
        if (UserManager.getUserBean().getLocation_code() <= 0) {
            if (PrefHelper.incInt("task_center_click_times") > 4) {
                Logs.d("task_center_click_times " + PrefHelper.incInt("task_center_click_times"));
                Router.turnTo(mContext, TaskCenterActivity.class)
                        .checkLogin(true)
                        .start();
                return;
            }
            LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (lm.getAllProviders().contains(LocationManager.GPS_PROVIDER) && !lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                UiHelper.showConfirmActionDialog(mContext, "请先开启GPS功能", (dialog2, which2) -> {
                    Intent intent1 = new Intent();
                    intent1.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent1, 1315);
                });
                return;
            } else {
                trySynAdCode();
            }
        }
        Router.turnTo(mContext, TaskCenterActivity.class)
                .checkLogin(true)
                .start();
    }
}
